<template>
  <NavBar showBack floating title="编辑资料"></NavBar>
  <form @submit="onSubmit">
    <view class="set-user-page bg-nav-bar-1">
      <view class="set-user-content">
        <view class="user-title">
          <Title icon="title-icon1" title="编辑资料"></Title>
        </view>
        <Cell rightArrow title="头像" opentype="chooseAvatar" @chooseavatar="onChooseavatar">
          <image name="avatar" class="user-head" :src="info.avatar"></image>
        </Cell>
        <Cell title="昵称">
          <input name="nickname" :value="info.nickname" type="nickname" placeholder="请输入您的昵称" />
        </Cell>
        <!-- <Cell title="手机号">
        <input v-model="info.mobile" type="nickname" disabled placeholder="请输入您的手机号" />
      </Cell> -->
      </view>
    </view>
    <view class="bottom-btn">
      <button class="btn" formType="submit">确定</button>
    </view>
  </form>
</template>


<script setup>
import { reactive, watch } from "vue"
import NavBar from "@/components/ui/nav-bar"
import Title from "@/components/ui/title"
import Cell from "@/components/ui/cell"
import { useUserInfoStore } from '@/path/store/userInfo';
import service, { uploadFile } from "@/path/service"
import { router } from "@/path/router";

const userStore = useUserInfoStore()
const info = reactive({
  nickname: "",
  avatar: "",
})
watch(() => userStore.userInfo, (ev) => {
  info.nickname = ev.nickname
  info.avatar = ev.avatar
}, { immediate: true, deep: true })

function onChooseavatar(ev) {
  const { avatarUrl } = ev.detail
  uploadFile({
    url: "api/common/upload",
    filePath: avatarUrl,
    name: "file",
  }).then((res) => {
    info.avatar = res.fullurl
  })
}

function onSubmit({ detail }) {
  if (!detail.value.nickname) {
    uni.showToast({
      title: "请输入名称",
      icon: "none"
    })
    return
  }
  service.post("api/user/profile", {
    ...info,
    nickname: detail.value.nickname
  }).then(() => {
    return userStore.getUserInfo()
  }).then(() => {
    router.back({ data: userStore.userInfo })
  })
}
</script>

<style lang="less" scoped>
@import url(./index.less);
</style>

